﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using UnityEngine.UI;
using System;

public class ScreenShot : MonoBehaviour {

    private Camera arCamera;

	// Use this for initialization
	void Start () {
        arCamera = GameObject.Find("ARCamera").GetComponent<Camera>();
	}
	
	// Update is called once per frame
	void Update () {
		
	}

    public void OnScreenShotClick()
    {
        ToastUtil.showToast("OnScreenShotClick invoked");

        try
        {
            System.DateTime now = System.DateTime.Now;
            string times = now.ToString();
            times = times.Trim();
            times = times.Replace("/", "-");

            string fileName = "ARScreenShot" + times + ".png";

            if (Application.platform == RuntimePlatform.Android)
            {
                //包含UI
                //Texture2D texture = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);
                //texture.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
                //texture.Apply();

                //byte[] bytes = texture.EncodeToPNG();

                //string destination = "/sdcard/DCIM/Screenshots";

                //if (!Directory.Exists(destination))
                //{
                //    Directory.CreateDirectory(destination);
                //}

                //string pathSave = destination + "/" + fileName;

                //File.WriteAllBytes(pathSave, bytes);


                //不包含UI

                RenderTexture rt = new RenderTexture(Screen.width,Screen.height,1);
                arCamera.targetTexture = rt;
                arCamera.Render();

                RenderTexture.active = rt;

                Texture2D texture = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);
                texture.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
                texture.Apply();

                arCamera.targetTexture = null;
                RenderTexture.active = null;
                Destroy(rt);


                byte[] bytes = texture.EncodeToPNG();

                //string destination = "/sdcard/DCIM/Camera"; //使用 /sdcard/DCIM/Screenshots 没有权限
                string cameraDir = PathUtil.getSdPath() + "/DCIM/Camera";

                ToastUtil.showToast("获取到 sdDir = " + cameraDir);

                if (!Directory.Exists(cameraDir))
                {
                    Directory.CreateDirectory(cameraDir);
                }

                string pathSave = cameraDir + "/" + fileName;

                File.WriteAllBytes(pathSave, bytes);

                ToastUtil.showToast("OnScreenShotClick finished");
            }
        }
        catch (Exception e)
        {
            ToastUtil.showToast("OnScreenShotClick exception = " + e.Message);
        }
    }
}

